from typing import List, Optional
from dataclasses import dataclass
from .domain_classifier import handle_query
from logging import getLogger

logger = getLogger('pet_ai')

@dataclass
class GPTResponse:
    text: str
    confidence: float

class PetGPT:
    """领域受限的生成模型"""
    def generate(self, query: str) -> GPTResponse:
        # TODO: 实现领域受限的生成逻辑
        return GPTResponse(text="示例回答", confidence=0.9)

class VectorSearch:
    """向量搜索引擎"""
    def __init__(self, index: str):
        self.index = index

    def find_similar(self, query: str) -> List[str]:
        """查找相似商品"""
        # TODO: 实现向量搜索逻辑
        return ["商品1", "商品2", "商品3"]
    
    def search(self, query: str) -> str:
        """直接商品搜索"""
        # TODO: 实现商品搜索逻辑
        return "搜索结果"

class PetAssistant:
    """智能问答与商品检索协同"""
    def __init__(self):
        self.gpt = PetGPT()  # 领域受限的生成模型
        self.search_engine = VectorSearch(index='pet_products')

    async def respond(self, query: str) -> str:
        """处理用户查询"""
        # 首先进行领域判断
        non_pet_response = await handle_query(query)
        if non_pet_response:
            logger.info(f"非宠物领域响应：{non_pet_response}")
            return non_pet_response

        # 知识问答优先
        answer = self.gpt.generate(query)
        logger.info(f"生成回答，置信度：{answer.confidence}")

        if answer.confidence > 0.8:
            related_products = self.search_engine.find_similar(query)
            logger.info(f"找到相关商品：{related_products[:3]}")
            return self._format_response(answer, related_products[:3])

        # 直接商品搜索
        result = self.search_engine.search(query)
        logger.info(f"商品搜索结果：{result}")
        return result

    def _format_response(self, answer: GPTResponse, products: List[str]) -> str:
        """格式化响应"""
        product_list = "\n".join([f"- {p}" for p in products])
        return f"{answer.text}\n\n相关推荐商品：\n{product_list}"
